package com.atguigu.gulimall.product.config;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Yanglinfengkk
 * 配置线程池
 * EnableConfigurationProperties    开启@ConfigurationProperties自定义配置参数
 */
@Configuration
//@EnableConfigurationProperties(ThreadPoolConfigProperties.class)
public class MyThreadConfig {

    /**
     * 七大参数
     *      corePoolSize    核心线程数[一直存在,除非(allowCoreThreadTimeOut)]:线程池创建好以后就准备就绪的线程数量,就等待来接收异步任务去执行
     *              5个  Thread thread = new  Thread();  thread.start();
     *      maximumPoolSize  最大线程数:控制资源并发
     *      keepAliveTime    存活时间,如果当前线程数量大于核心线程数
     *              释放空闲线程(maximumPoolSize-corePoolSize),只要线程空闲大于指定的keepAliveTime
     *      unit              时间单位
     *      BlockingQueue<Runnable> workQueue   阻塞队列:如果任务有很多,就会将目前多的任务放在队列中里面
     *              只要有线程空闲,就会去队列里面取出新的任务继续执行
     *      threadFactory    线程的创建工厂
     *      RejectedExecutionHandler handler    如果队列满了,按照我们指定的拒绝策略拒绝执行任务
     * 如果不想抛弃还要执行,CallerRunsPolicy拒绝策略
     */
    @Bean
    public ThreadPoolExecutor threadPoolExecutor(ThreadPoolConfigProperties configProperties){
        return new ThreadPoolExecutor(configProperties.getCoreSize(),
                configProperties.getMaxSize(),
                configProperties.getKeepAliveTime(),
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(100000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
    }
}
